<template>
    <div id="content">
        <div id="map" ref="map"></div>
        <h1 id="msg"></h1>
        <div class="btns">
            <button @click="startRect" id="btn_select" v-show="rectangleBtn">开启框选</button>
            <button @click="cancelRect" v-show="!rectangleBtn">取消框选</button>
        </div>
    </div>
</template>

<script>
    import "ol/css";
    import {Map, View, Feature} from "ol";
    import XYZ from "ol/source/XYZ";
    import TileLayer from "ol/layer/Tile";

    import {Vector as VectorSource} from "ol/source";
    import {Vector as VectorLayer, Vector as RectangleLayer, Vector as PointCenterLayer} from "ol/layer";
    import {Polygon, LineString, Point} from "ol/geom";
    import {Style, Circle as CircleStyle, Stroke, Fill} from "ol/style";
    import {Draw} from "ol/interaction";
    import {createBox} from "ol/interaction/Draw";
    import {getCenter} from 'ol/extent';

    export default {
        name: "AppRectangleSelect3",
        data() {
            return {
                map: null,
                rectangleLayerCache: [],//缓存每次框选的矩形层
                rectangleDraw: null,
                rectangleBtn: true,
                vectorLayer: null,//业务数据层
                pointCenterLayer: null,//中心点业务层
            };
        },
        methods: {

            //框选操作
            startRect() {
                // 选择要素事件开始
                const btn_select = document.getElementById("btn_select");
                btn_select.addEventListener("click", () => {
                    this.rectangleBtn = false;

                    // this.map.removeInteraction(this.rectangleDraw);
                    // this.map.removeLayer(this.pointLayer);//框选产生的中心点

                    let source = new VectorSource();
                    this.rectangleDraw = new Draw({
                        source: source,
                        type: "Circle",
                        style: new Style({
                            // 将点设置成圆形样式
                            image: new CircleStyle({
                                fill: new Fill({
                                    color: "#F00",// 点的颜色
                                }),
                                radius: 5, // 圆形半径
                            }),
                            // 线样式
                            stroke: new Stroke({
                                color: "#0F0",
                                lineCap: "round", // 设置线的两端为圆头
                                width: 5,
                            }),
                        }),

                        geometryFunction: createBox(), // 使画出来的现状为矩形
                    });

                    this.map.addInteraction(this.rectangleDraw);

                    this.rectangleDraw.on("drawend", (evt) => {
                        if (this.rectangleLayerCache.length > 0) {//如果前面有绘制数据，则删除
                            for (let index = 0; index < this.rectangleLayerCache.length; index++) {
                                if (this.rectangleLayerCache[index]) {
                                    console.log('执行清除操作：', this.rectangleLayerCache[index])
                                    this.rectangleLayerCache[index].getSource().clear();
                                    this.map.removeLayer(this.rectangleLayerCache[index]);
                                }
                            }
                            this.rectangleLayerCache.clear;
                        }

                        let rectangleLayer = new RectangleLayer({
                            source: source,
                        });
                        this.map.addLayer(rectangleLayer);
                        this.rectangleLayerCache.push(rectangleLayer);

                        var polygon = evt.feature.getGeometry();
                        setTimeout(() => {
                            var extent = polygon.getExtent();
                            var features = this.vectorLayer.getSource().getFeaturesInExtent(extent); //先缩小feature的范围
                            var str = "";
                            for (var i = 0; i < features.length; i++) {
                                var featureItem = features[i]
                                var selectedF = featureItem.getGeometry();
                                var selectedCoord = selectedF.getCoordinates();
                                console.log('选中的坐标点：', featureItem.get('name'), selectedCoord)
                                if (str == "") {
                                    str += features[i].get('name');//注意方法是get
                                } else {
                                    str += "," + features[i].get('name');
                                }
                            }
                            document.getElementById('msg').innerText = str;
                            var centerPoint = getCenter(extent);   //获取边界区域的中心位置
                            console.log("框选结束--框选区域中心位置为：", centerPoint);
                            this.map.getView().animate({
                                center: centerPoint,
                                duration: 500,
                            });//设置当前地图的显示中心位置

                            this.createPoint(centerPoint);

                        }, 300);
                    });

                });


            },

            createPoint(centerPoint) {
                if (this.pointCenterLayer != null) {
                    this.map.removeLayer(this.pointCenterLayer)
                }
                this.pointCenterLayer = new PointCenterLayer({
                    className: 'pointCenterClass',
                    source: new VectorSource()
                });
                // 循环添加feature
                //把要素集合添加到图层
                const feature = new Feature({
                    geometry: new Point(centerPoint),
                });
                feature.setStyle(
                    new Style({
                        image: new CircleStyle({
                            radius: 12, fill: new Fill({color: '#FF0000',})
                        }),
                        // image: new Icon({
                        //   scale: 0.8,
                        //   src: require('@/assets/virusLogo.png'),//TODO:需要美化图片？？
                        //   anchor:[0.48,0.52],
                        //   imgSize: [80, 50]
                        // })
                    })
                )

                feature.obj = {
                    id: '0000',
                    water_name: '随机定位',
                    east_longi: centerPoint[0],
                    north_lati: centerPoint[1]
                };

                this.pointCenterLayer.getSource().addFeatures([feature]);
                // 添加图层
                this.map.addLayer(this.pointCenterLayer);
            },

            //取消框选
            cancelRect() {
                this.map.removeInteraction(this.rectangleDraw);
                if (this.rectangleLayerCache.length > 0) {//如果前面有绘制数据，则删除
                    for (let index = 0; index < this.rectangleLayerCache.length; index++) {
                        if (this.rectangleLayerCache[index]) {
                            console.log('执行清除操作：', this.rectangleLayerCache[index])
                            this.rectangleLayerCache[index].getSource().clear();
                            this.map.removeLayer(this.rectangleLayerCache[index]);
                        }
                    }
                    this.rectangleLayerCache.clear;
                }

                if (this.pointCenterLayer) {
                    this.map.removeLayer(this.pointCenterLayer);//框选产生的中心点
                }

                this.rectangleBtn = true;
            },

            createMap() {
                // 创建要素图层
                this.vectorLayer = new VectorLayer({
                    source: new VectorSource({
                        features: [
                            new Feature({
                                geometry: new Polygon([[
                                    [119.0, 29.0],
                                    [119.2, 29.0],
                                    [119.2, 29.2],
                                    [119.0, 29.2],
                                    [119.0, 29.0]
                                ]]),
                                name: 'A'
                            }),
                            new Feature({
                                geometry: new Polygon([[
                                    [119.4, 29.0],
                                    [119.6, 29.0],
                                    [119.5, 29.2],
                                    [119.4, 29.0]
                                ]]),
                                name: 'B'
                            }),
                            new Feature({
                                geometry: new LineString([
                                    [119.0, 29.4],
                                    [119.2, 29.3],
                                    [119.4, 29.5],
                                    [119.6, 29.3],
                                    [119.8, 29.6]
                                ]),
                                name: 'C'
                            }),
                            new Feature({
                                geometry: new Point([119.4, 29.6]),
                                name: 'D'
                            }),
                        ]
                    }),
                    style: new Style({
                        image: new CircleStyle({
                            radius: 30,
                            stroke: new Stroke({
                                width: 4,
                                color: 'blue'
                            }),
                            fill: new Fill({
                                color: 'yellow'
                            })
                        }),
                        stroke: new Stroke({
                            width: 4,
                            color: 'blue'
                        }),
                        fill: new Fill({
                            color: 'yellow'
                        })
                    })
                });

                var gaodeLayer = new TileLayer({
                    source: new XYZ({
                        url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
                    })
                });
                // 创建地图
                this.map = new Map({
                    target: 'map',
                    layers: [
                        gaodeLayer,
                        this.vectorLayer,
                    ],
                    view: new View({
                        projection: 'EPSG:4326',
                        center: [119.2, 29.2],
                        zoom: 10
                    })
                });
            }
        },

        mounted() {
            this.createMap();
            this.startRect();
        }
    };
</script>
<style lang="scss" scoped>
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 50px;
        left: 50px;
    }

    /*移除OSM的链接*/
    :deep(.ol-attribution) {
        display: none;
    }

    .btns {
        /*position: absolute;*/
        top: 0px;
        left: 0px;
    }
</style>